/**
 * @file workflowAPI.js
 * @description Dify Workflow API服务，用于AI决策支持系统
 * @created 2024-07-17
 */

import axios from 'axios';

// Dify API配置
const WORKFLOW_API_KEY = 'app-pRGQbFwKawC85Ao1TUCG095w';
const DIFY_API_URL = 'http://121.40.242.43/v1';

// 创建一个axios实例，预设Authorization头
const workflowAxios = axios.create({
  baseURL: DIFY_API_URL,
  headers: {
    'Authorization': `Bearer ${WORKFLOW_API_KEY}`,
    'Content-Type': 'application/json'
  }
});

export const workflowAPI = {
  /**
   * 执行Workflow（阻塞模式）
   * @param {string} intent - 意图参数，决定执行哪种功能
   * @param {object} inputs - 输入参数
   * @param {string} userId - 用户标识
   * @returns {Promise} API响应
   */
  runWorkflow(intent, inputs = {}, userId = 'admin_user') {
    // 合并intent和其他输入参数
    const workflowInputs = {
      ...inputs,
      intent: intent
    };
    
    return workflowAxios.post('/workflows/run', {
      inputs: workflowInputs,
      response_mode: 'blocking',
      user: userId
    });
  },
  
  /**
   * 执行Workflow（流式模式）
   * @param {string} intent - 意图参数，决定执行哪种功能
   * @param {object} inputs - 输入参数
   * @param {string} userId - 用户标识
   * @returns {Promise<Response>} Fetch API响应，用于处理SSE
   */
  async runWorkflowStreaming(intent, inputs = {}, userId = 'admin_user') {
    // 合并intent和其他输入参数
    const workflowInputs = {
      ...inputs,
      intent: intent
    };
    
    const response = await fetch(`${DIFY_API_URL}/workflows/run`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${WORKFLOW_API_KEY}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        inputs: workflowInputs,
        response_mode: 'streaming',
        user: userId
      })
    });
    
    return response;
  },
  
  /**
   * 处理SSE流式响应
   * @param {Response} response - fetch API的响应对象
   * @param {function} onNodeFinished - 节点完成回调
   * @param {function} onWorkflowFinished - 工作流完成回调
   * @param {function} onError - 错误处理回调
   */
  handleStreamResponse(response, onNodeFinished, onWorkflowFinished, onError) {
    if (!response.ok) {
      throw new Error(`API请求失败: ${response.status} ${response.statusText}`);
    }
    
    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let buffer = '';
    
    function processStream() {
      return reader.read().then(({ done, value }) => {
        if (done) {
          if (buffer.trim()) {
            // 处理缓冲区中剩余的数据
            processChunk(buffer);
          }
          return;
        }
        
        // 解码并添加到缓冲区
        buffer += decoder.decode(value, { stream: true });
        
        // 按 data: 行分割并处理
        const lines = buffer.split('\n\n');
        buffer = lines.pop() || ''; // 最后一行可能不完整，保留在缓冲区
        
        lines.forEach(processChunk);
        
        // 继续读取流
        return processStream();
      }).catch(error => {
        if (onError) onError(error);
      });
    }
    
    function processChunk(chunk) {
      // 移除 "data: " 前缀
      const dataString = chunk.replace(/^data: /, '');
      if (!dataString.trim()) return;
      
      try {
        const data = JSON.parse(dataString);
        
        // 根据事件类型处理不同的事件
        switch (data.event) {
          case 'node_finished':
            if (onNodeFinished) onNodeFinished(data);
            break;
          case 'workflow_finished':
            if (onWorkflowFinished) onWorkflowFinished(data);
            break;
          case 'error':
            if (onError) onError(new Error(data.message || '未知错误'));
            break;
        }
      } catch (error) {
        console.error('解析SSE数据出错:', error, dataString);
        if (onError) onError(error);
      }
    }
    
    // 开始处理流
    processStream();
  },
  
  /**
   * 停止响应
   * @param {string} taskId - 任务ID
   * @param {string} userId - 用户标识
   * @returns {Promise} API响应
   */
  stopResponse(taskId, userId = 'admin_user') {
    return workflowAxios.post(`/workflows/tasks/${taskId}/stop`, {
      user: userId
    });
  },
  
  /**
   * 获取应用配置信息
   * @param {string} userId - 用户标识
   * @returns {Promise} API响应
   */
  getParameters(userId = 'admin_user') {
    return workflowAxios.get(`/parameters?user=${userId}`);
  },
  
  /**
   * 获取workflow执行情况
   * @param {string} workflowId - workflow执行ID
   * @returns {Promise} API响应
   */
  getWorkflowRun(workflowId) {
    return workflowAxios.get(`/workflows/run/${workflowId}`);
  },
  
  /**
   * 获取workflow日志
   * @param {object} params - 查询参数
   * @returns {Promise} API响应
   */
  getWorkflowLogs(params = {}) {
    return workflowAxios.get('/workflows/logs', { params });
  },
  
  /**
   * 测试API连接
   * @returns {Promise} 测试结果
   */
  testConnection() {
    return workflowAxios.get('/');
  }
};

export default workflowAPI; 